package com.rzwl.single.server.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.beans.PropertyDescriptor;
import java.util.HashSet;
import java.util.Set;

/**
 * @author : championjing
 * @Description:
 * @Date: 2020/2/10
 */
public class CopyObject {

    /**
     *  src -> target
     * @param src
     * @param target
     */
    public static void copyProp(Object src, Object target) {
        BeanUtils.copyProperties(src, target, igronKeys(src));
    }

    /**
     * 获取忽略的属性
     * @param o
     * @return
     */
    private static String[] igronKeys(Object o) {
        final BeanWrapper src = new BeanWrapperImpl(o);
        PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> keys = new HashSet<String>();
        for (PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) {
                keys.add(pd.getName());
            } else if (StringUtils.isBlank( srcValue.toString() )) {
                keys.add(pd.getName());
            }
        }
        String[] result = new String[keys.size()];
        return keys.toArray(result);
    }

}
